﻿using ComLib;
using ComLib.ComFun;
using ComUIControl;
using KFormBase;
using LogLib;
using MainForm;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace MainForms
{
    static class Program
    {
        private static AppConfig _appConfig = null;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {          
            bool isRuned;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, "IPTMainForm", out isRuned);
            if (isRuned)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                ModifyInMemory.ActivateMemoryPatching();
                OnStartup();        
            }
            else
            {
                MsgBox.Show("提示: 不能重复打开该程序。\n自助照相程序已经启动了!");
            }                      
        }

        /// <summary>
        /// 配置文件初始化
        /// </summary>
        /// <returns></returns>
        private static void OnStartup()
        {
            //string appName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            string appName = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
            ModuleAppManager appManager = ModuleAppManager.Instance;
            if(appManager.Init(appName))
            {
                //AsyncTask.StartDelayTask(2, () => SendKeys.Send("^%{RIGHT}"), this);
                //不隐藏任务栏
                //ShowTaskBar(false);
                //ShowStartButton(false);

                SendKeys.SendWait("^%{RIGHT}");

                //allow UI with ApartmentState.STA though[STAThread] above should give that to you
                //var thread = new Thread(ThreadStart);
                //thread.TrySetApartmentState(ApartmentState.STA);
                //thread.IsBackground = false;
                //thread.Start();

                //检查注册码
                //string key = IniConfigFile.IniValue("Info", "kc", "", "");
                //string machineCode = "";
                //if (!RegCodeCheck.CheckRegCode(key, ref machineCode))
                //{
                //    frmReg frmReg = new frmReg(machineCode);
                //    var ret = frmReg.ShowDialog();
                //    if (ret == DialogResult.Cancel)
                //    {
                //        return;
                //    }
                //}

                AppService service = AppService.Get();
                _appConfig = service.Config;
                if(_appConfig.UserDualScreen)
                {
                    Application.Run(new MultiFormContext(new MainForm(true), new MainForm(false)));
                }
                else
                {
                    Application.Run(new MainForm(true));
                }
            }
            else
            {
                MsgBox.Show(appManager.Error);
            }
        }

        private static void ThreadStart()
        {
            // <-- other form started on its own UI thread
            Thread.Sleep(1000);
            Application.Run(new MainForm(false));
        }

        public static void ShowTaskBar(bool showCode)
        {
            IntPtr hwnd = IntPtr.Zero;
            hwnd = WinAPI.FindWindow("Shell_TrayWnd", "");//获取任务栏的句柄
            if (hwnd == IntPtr.Zero) return;
            if (showCode)
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_SHOW);//显示任务栏
            }
            else
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_HIDE);//隐藏任务栏
            }
        }

        public static void ShowStartButton(bool showCode)
        {
            IntPtr hwnd = IntPtr.Zero;
            hwnd = WinAPI.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Button", "开始");//获取开始按钮的句柄
            if (hwnd == IntPtr.Zero) return;
            if (showCode)
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_SHOW);//显示开始按钮
            }
            else
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_HIDE);//隐藏开始按钮
            }
        }

        /// <summary>
        /// 线程异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            //在此处添加上你要写日志的方法
            Log.WriteAsync(e.Exception.Message);
            Log.WriteExceptionAsync(e.Exception.ToString());
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Log.WriteAsync(e.ToString());
            Log.WriteExceptionAsync(e.ExceptionObject.ToString());
        }
    }
}
